package cn.shujuhai.qtadmin.platform.pluging.security;

import java.io.IOException;

import org.jetbrains.annotations.NotNull;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.shujuhai.qtadmin.platform.kit.CommonKit;
import cn.shujuhai.qtadmin.platform.pluging.result.Result;

/**
 * session超时或被踢下线后的处理策略
 *
 * @author dch798
 * @date 2021/08/26 22:53
 **/
public class CustomExpiredSessionStrategy implements SessionInformationExpiredStrategy {

    @Override
    public void onExpiredSessionDetected(@NotNull SessionInformationExpiredEvent sessionInformationExpiredEvent)
        throws IOException {
        if (CommonKit.isJson(sessionInformationExpiredEvent.getRequest())) {
            ObjectMapper objectMapper = new ObjectMapper();
            sessionInformationExpiredEvent.getResponse().setContentType("application/json; charset=UTF-8");
            sessionInformationExpiredEvent.getResponse().getWriter()
                .write(objectMapper.writeValueAsString(Result.failure("您的登陆已经超时或在另一台机器登陆，您被迫下线")));
        } else {
            RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
            redirectStrategy.sendRedirect(sessionInformationExpiredEvent.getRequest(),
                sessionInformationExpiredEvent.getResponse(), "");
        }
    }
}
